package com.xhwl.data.controller;


import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.sdata.FileUploadRecord;
import com.xhwl.common.pojo.cent.sdata.StaffCertificate;
import com.xhwl.common.utils.StringUtils;
import com.xhwl.data.service.IFileUploadRecordService;
import com.xhwl.data.util.BASE64DecodedMultipartFile;
import com.xhwl.data.util.SslUtils;
import com.xhwl.starter.obs.IObsService;
import com.xhwl.starter.redisson.enums.FileTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;


/**
 * @Author JCccc
 * @Description
 * @Date 2021/8/5 15:22
 */
@RestController
public class UploadController {

    @Autowired
    IObsService obsService;

    @Autowired
    private IFileUploadRecordService fileUploadRecordService;

    /**
     * 上传图片到华为 obs
     *
     * @param file
     * @return
     */
    @PostMapping("/upload/img")
    public ResultJson uploadImg(@RequestParam("file") MultipartFile file) {
        String url = null;
        try {
            if (!checkFileType(file)){
                return ResultJson.fail("暂不支持上传该格式");
            }
            byte[] byteArr = file.getBytes();
            InputStream inputStream = new ByteArrayInputStream(byteArr);
            url = obsService.uploadImg(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
            return ResultJson.fail("上传失败");
        }
        return ResultJson.success("上传成功", url);
    }

    private Boolean checkFileType(MultipartFile file){
        String fileType = file.getOriginalFilename().split("\\.")[file.getOriginalFilename().split("\\.").length-1];
        String fileTypeToLower = fileType.toLowerCase();
        if (!FileTypeEnum.isDefined(fileTypeToLower)){
            return false;
        }
        return true;
    }
    /**
     * 多张图片上传
     *
     * @param files
     * @return
     */
    @PostMapping("/upload/imgs")
    public ResultJson uploadImgs(@RequestParam("files") MultipartFile files[]) {
        List<String> urls = new ArrayList<>();
        try {
            for (MultipartFile file : files) {
                if (!checkFileType(file)){
                    return ResultJson.fail("暂不支持上传该格式");
                }
                byte[] byteArr = file.getBytes();
                InputStream inputStream = new ByteArrayInputStream(byteArr);
                String url = obsService.uploadImg(inputStream);
                urls.add(url);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return ResultJson.fail("上传失败");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultJson.success("上传成功", urls);
    }

    /**
     * 图片上传(不用授权)
     *
     * @param file
     * @return
     */
    @PostMapping("/upload/img-open")
    public ResultJson uploadImgOpen(@RequestParam("file") MultipartFile file) {
        String url = null;
        try {
            if (!checkFileType(file)){
                return ResultJson.fail("暂不支持上传该格式");
            }
            byte[] byteArr = file.getBytes();
            InputStream inputStream = new ByteArrayInputStream(byteArr);
            url = obsService.uploadImg(inputStream);
            // 保存记录
            FileUploadRecord fileUploadRecord = new FileUploadRecord();
            fileUploadRecord.setUrl(url);
            // 未确认状态
            fileUploadRecord.setStatus((short) 1);
            fileUploadRecordService.save(fileUploadRecord);
        } catch (IOException e) {
            e.printStackTrace();
            return ResultJson.fail("上传失败");
        }
        return ResultJson.success("上传成功", url);
    }


    /**
     * 上传图片到华为 obs
     *
     * @param
     * @return
     */
    @PostMapping("/upload/imgBase64")
    public ResultJson uploadImgBase64(@RequestParam("base64ImageUrl") String base64ImageUrl) {
        //"data:image/png;base64," 这个头规则加到base64上后，就可以直接显示到网页上了
        String avatar = "data:image/png;base64," + base64ImageUrl;
        MultipartFile file = BASE64DecodedMultipartFile.base64ToMultipart(avatar);
        String url = null;
        try {
            byte[] byteArr = file.getBytes();
            InputStream inputStream = new ByteArrayInputStream(byteArr);
            url = obsService.uploadImg(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
            return ResultJson.fail("上传失败");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultJson.success("上传成功", url);
    }


    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @PostMapping("/upload/file")
    public ResultJson uploadFile(@RequestParam("file") MultipartFile file) {
        String url = null;
        String originalFileName = file.getOriginalFilename();
        if (StringUtils.isEmpty(originalFileName)) {
            return ResultJson.fail("文件名不能为空");
        }
        if (!checkFileType(file)){
            return ResultJson.fail("暂不支持上传该格式");
        }
        String suffix = Objects.requireNonNull(originalFileName).substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        try {
            byte[] byteArr = file.getBytes();
            InputStream inputStream = new ByteArrayInputStream(byteArr);
            String mdFileName = UUID.randomUUID().toString().replace("-", "") + "." + suffix;
            url = obsService.putObject(mdFileName, inputStream, file.getOriginalFilename());
            //保留原文件名的方式
            //   url = obsService.putObject(originalFileName,inputStream,null);
        } catch (IOException e) {
            e.printStackTrace();
            return ResultJson.fail("上传失败");
        }
        return ResultJson.success("文件上传成功", url);
    }


    @PostMapping("/upload/pictureUrl")
    public ResultJson uploadPictureUrl(String pictureUrl) {
        InputStream inputStream = null;
        String picUrl;
        try {
            // 构造URL
            URL url = new URL(pictureUrl);
            SslUtils.ignoreSsl();
            // 打开连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //通过输入流获取图片数据
            inputStream = conn.getInputStream();
            picUrl = obsService.uploadImg(inputStream);
            inputStream.close();
        } catch (Exception e) {
            throw new RuntimeException("Failed to upload image," + e.getMessage());
        } finally {
            if (inputStream != null) {
                // 完毕，关闭所有链接
                try {
                    inputStream.close();
                } catch (Exception e) {
                    throw new RuntimeException("Failed close all links," + e.getMessage());
                }
            }
        }
        return ResultJson.success("上传成功", picUrl);
    }

    /**
     * 上传员工资格证书，最多6张，每张最大5M
     * @param files
     * @return
     */
    @PostMapping("/upload/certificates")
    public ResultJson uploadCertificates(@RequestParam("files") List<MultipartFile> files) {
        List<StaffCertificate> StaffCertificateList = new ArrayList<>();

        try {
            for (MultipartFile file : files) {
                if (!checkFileType(file) || StaffCertificateList.size() >= 6) {
                    // 如果文件类型不支持或已经上传了6张图片，则跳过
                    continue;
                }
                byte[] byteArr = file.getBytes();
                InputStream inputStream = new ByteArrayInputStream(byteArr);
                String url = obsService.uploadImg(inputStream);

                // 存储图片链接和文件名称
                StaffCertificate staffCertificate = new StaffCertificate();
                staffCertificate.setCertificateName(file.getOriginalFilename());
                staffCertificate.setCertificateUrl(url);
                StaffCertificateList.add(staffCertificate);
            }
            return ResultJson.success("上传成功",StaffCertificateList);
        } catch (IOException e) {
            e.printStackTrace();
            return ResultJson.fail("上传失败");
        }
    }
}
